package com.miyake.rest;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class XmlSerializer {
    public static synchronized String serialize(Object object) {
        try {
            Serializer serializer = new Persister();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            serializer.write(object, os);
            String xml = new String(os.toByteArray());
            os.close();
            
            return xml;
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static synchronized <M> M deserialize(InputStream is, Class<M> cls) {
        Serializer serializer = new Persister();
        try {
            return serializer.read(cls, is);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static synchronized <M> M deserialize(String xml, Class<M> cls) {
        Serializer serializer = new Persister();
        try {
            return serializer.read(cls, xml);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
